package com.hanscan.persistence.controllers;


import com.hanscan.persistence.EntityManagerSingleton;
import com.hanscan.persistence.controllers.exceptions.BirthDateNullException;
import com.hanscan.persistence.controllers.exceptions.NonexistentEntityException;
import com.hanscan.persistence.controllers.exceptions.NspNullException;
import com.hanscan.persistence.controllers.exceptions.UserTypeNullException;
import com.hanscan.persistence.entities.BioTemplate;
import com.hanscan.persistence.entities.User;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;



public class UserJpaController implements Serializable
{

    public UserJpaController()
    {
    }

    public EntityManager getEntityManager()
    {
        return EntityManagerSingleton.getInstance();
    }

    public void create(User user) throws Exception
    {
        if (user.getBirthday() == null)
        {
            throw new BirthDateNullException("birthDate is null");
        }

        if (user.getNsp() == null)
        {
            throw new NspNullException("Nsp is null");
        }

        if (user.getUserType() == null)
        {
            throw new UserTypeNullException("userType is 0");
        }

        try
        {
           User userAux = findUsersByNsp(user.getNsp());
           BioTemplate bioTemplate = userAux.getBioTemplates().get(0);
           bioTemplate.setTemplateData(user.getBioTemplates().get(0).getTemplateData());


           EntityManager em = null;
           try
           {
                em = getEntityManager();
                em.getTransaction().begin();
                em.merge(bioTemplate);
                //em.persist(user);
                em.getTransaction().commit();
           }
           catch (Exception ex2)
           {
                throw ex2;
           }
            

        }
        catch (NonexistentEntityException ex)
        {
            EntityManager em = null;
            try
            {
                em = getEntityManager();
                em.getTransaction().begin();
                em.persist(user.getBioTemplates().get(0));
                em.persist(user);
                em.getTransaction().commit();
            }
            catch (Exception ex2)
            {
                throw ex2;
            }
        }

    }

    public void edit(User user) throws NonexistentEntityException, Exception
    {
        if (user.getBirthday() == null)
        {
            throw new BirthDateNullException("birthDate is null");
        }

        if (user.getNsp() == null)
        {
            throw new NspNullException("Nsp is null");
        }

        if (user.getUserType() == null)
        {
            throw new UserTypeNullException("userType is 0");
        }


        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            user = em.merge(user);
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void destroy(User user) throws Exception
    {
        //TODO: comprobaciones
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            em.remove(user);
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public List<User> findUserEntities()
    {
        return findUserEntities(true, -1, -1);
    }

    public List<User> findUserEntities(int maxResults, int firstResult)
    {
        return findUserEntities(false, maxResults, firstResult);
    }

    private List<User> findUserEntities(boolean all, int maxResults,
            int firstResult)
    {
        EntityManager em = getEntityManager();

        Query q = em.createQuery("select object(o) from User as o");
        if (!all)
        {
            q.setMaxResults(maxResults);
            q.setFirstResult(firstResult);
        }
        return q.getResultList();     
    }

    public User findUserById(Long id) throws NonexistentEntityException
    {
        EntityManager em = getEntityManager();
        User user = null;
        em.clear();

        try
        {
            Query query = em.createNamedQuery("findUserById");
            query.setParameter(1, id);
            user = (User) query.getSingleResult();
            return user;
        }
        catch (NoResultException ex)
        {
            throw new NonexistentEntityException(ex.getMessage());
        }

    }

    /**
     *
     * @param nsp
     * @return
     * @throws com.hanscan.controllers.exceptions.NonexistentEntityException
     */
    public User findUsersByNsp(String nsp) throws
            NonexistentEntityException
    {
        EntityManager em = getEntityManager();
        User user = null;
        nsp = nsp.toUpperCase();
        try
        {
            Query query = em.createNamedQuery("findUserByNsp");
            query.setParameter(1, nsp);
            user = (User) query.getSingleResult();
            return user;
        }
        catch (NoResultException ex)
        {
            ex.printStackTrace();
            throw new NonexistentEntityException(ex.getMessage());
        }
        catch (Exception ex)
        {
            throw new NonexistentEntityException(ex.getMessage());
        }
    }

    public int getUserCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            Query q = em.createQuery("select count(o) from User as o");
            return ((Long) q.getSingleResult()).intValue();
        }
        finally
        {
            em.close();
        }
    }

    /**
     * 
     * @param birhtDate
     * @param gender
     * @return
     * @throws com.hanscan.controllers.exceptions.NonexistentEntityException
     */
    public List<User> findUsersByBirthDateAndGender( Date birhtDate,boolean gender)
            throws NonexistentEntityException
    {
        
        EntityManager em = getEntityManager();
        List<User> users = null;
        try
        {
            System.out.println (" date.toString()... " +birhtDate.toString());
            Query query = em.createNamedQuery("findUsersByBirthDate");
            query.setParameter(1, birhtDate);
           // query.setParameter(2, gender);
            users = (List<User>) query.getResultList();
            return users;
        }
        catch (NoResultException ex)
        {
            throw new NonexistentEntityException(ex.getMessage());
        }
    }

    /**
     *
     * @param String userName
     * @param String password
     * @return  List<User>
     * @throws com.hanscan.controllers.exceptions.NonexistentEntityException
     */
    public User findClientByUserNameAndPassword(String userName, String password)
            throws NonexistentEntityException
    {
        EntityManager em = getEntityManager();

        try
        {
            Query query = em.createNamedQuery("findClientByUserNameAndPassword");
            query.setParameter(1, userName);
            query.setParameter(2, password);
            User user = (User) query.getSingleResult();
            return user;
        }
        catch (NoResultException ex)
        {
            throw new NonexistentEntityException(ex.getMessage());
        }
    }

    public List<User> findCompany(long idCompany)
            throws NonexistentEntityException
    {
        EntityManager em = getEntityManager();
        try
        {
            Query query = em.createNamedQuery("findCompany");
            query.setParameter(1, idCompany);
            List<User> listUser = query.getResultList();
            return listUser;
        }
        catch (NoResultException ex)
        {
            throw new NonexistentEntityException(ex.getMessage());
        }
    }

    public List<User> findUser(User user)
    {
        EntityManager em = getEntityManager();

        String queryS = "SELECT u FROM User u WHERE ";
        String name = user.getName();
        String surname1 = user.getSurname1();
        String surname2 = user.getSurname2();


        if(user.getName().equals(""))
        {
            queryS = queryS + " u.name= '"+name+"' ";
        }

        if(user.getSurname1().equals(""))
        {
            queryS = queryS + "AND u.surname1= '"+surname1+"' ";
        }

        if(user.getSurname2().equals(""))
        {
            queryS = queryS + "AND u.surname2= '"+surname2+"' ";
        }

        queryS = queryS + "and u.resigntDate is null";
        try
        {
            Query query = em.createNativeQuery(queryS);
            List<User> listUser = query.getResultList();
            return listUser;
        }
        catch (NoResultException ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

}
